class DrawSector {
  constructor(arg) {
    this.viewer = arg.viewer;
    this.Cesium = arg.Cesium;
    this.floatingPoint = null;
    this._sector = null;
    this._sectorLast = null;
    this._positions = [];
    this._entities_point = [];
    this._entities_sector = [];
    this._sectorData = null;
    this.DrawStartEvent = new Cesium.Event();
    this.DrawEndEvent = new Cesium.Event();
    this.bubblePopup = null;
    this.bubbleEntityInfo = null;
    this.clickHandler = null;
    this.objId = 'draw-sector-' + Date.now(); // 添加唯一ID
  }

  //返回扇形
  get sector() {
    return this._sectorLast;
  }

  //返回扇形数据用于加载扇形
  getData() {
    return this._sectorData;
  }

  // 修改编辑调用计算
  computePosition(data) {
    let $this = this;
    let pnts = data;
    let center = $this.lonLatToMercator($this.cartesianToLatlng(pnts[0]));
    let pnt2 = $this.lonLatToMercator($this.cartesianToLatlng(pnts[1]));
    let pnt3 = $this.lonLatToMercator($this.cartesianToLatlng(pnts[2]));
    var radius = $this.MathDistance(pnt2, center);
    var startAngle = $this.getAzimuth(pnt2, center);
    var endAngle = $this.getAzimuth(pnt3, center);
    var pList = $this.getArcPoints(center, radius, startAngle, endAngle);
    pList.push(pnts[0], pList[0]);
    let arrow = [];
    for (var i = 0; i < pList.length; i++) {
      var cart3 = new $this.Cesium.Cartesian3(pList[i].x, pList[i].y, pList[i].z);
      arrow.push(cart3);
    }
    var lnglatArr = [];
    for (var d = 0; d < data.length; d++) {
      lnglatArr.push($this.cartesianToLatlng(data[d]))
    }
    $this._sectorData = lnglatArr;
    return new $this.Cesium.PolygonHierarchy(arrow)
  }

  //加载扇形
  addload(data) {
    var $this = this;
    let pnts = data;
    let center = $this.lonLatToMercator(pnts[0]);
    let pnt2 = $this.lonLatToMercator(pnts[1]);
    let pnt3 = $this.lonLatToMercator(pnts[2]);
    var radius = $this.MathDistance(pnt2, center);
    var startAngle = $this.getAzimuth(pnt2, center);
    var endAngle = $this.getAzimuth(pnt3, center);
    var pList = $this.getArcPoints(center, radius, startAngle, endAngle);
    let pntsc = $this.Cesium.Cartesian3.fromDegrees(pnts[0][0], pnts[0][1])
    pList.push(pntsc, pList[0]);
    let arrow = [];
    for (var i = 0; i < pList.length; i++) {
      var cart3 = new $this.Cesium.Cartesian3(pList[i].x, pList[i].y, pList[i].z);
      arrow.push(cart3);
    }
    var arrowEntity = $this.viewer.entities.add({
      Type: 'DrawSector',
      Position: data,
      id: data.id || $this.objId,
      polygon: {
        hierarchy: new $this.Cesium.PolygonHierarchy(arrow),
        show: true,
        fill: true,
        clampToGround: true,
        material: $this.Cesium.Color.AQUA.withAlpha(0.9)
      }
    });
    return arrowEntity;
  }

  //开始创建
  startCreate() {
    var $this = this;
    this.handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    this.handler.setInputAction(function (evt) { //单机开始绘制
      //屏幕坐标转地形上坐标
      var cartesian = $this.getCatesian3FromPX(evt.position);
      if ($this._positions.length < 3) {
        $this.floatingPoint = $this.createPoint(cartesian);
        $this._positions.push(cartesian);
      }
      if (!$this._sector && $this._positions.length === 3) {
        $this._sector = $this.createsector();
      }
    }, $this.Cesium.ScreenSpaceEventType.LEFT_CLICK);

    this.handler.setInputAction(function (evt) { //移动时绘制面
      if ($this._positions.length < 2) return;
      var cartesian = $this.getCatesian3FromPX(evt.endPosition);
      if ($this._positions.length === 2) {
        $this._positions.push(cartesian);
        $this._sector = $this.createsector();
      } else if ($this._positions.length === 3) {
        $this._positions.pop();
        $this._positions.push(cartesian);
        if ($this._sector) {
          $this.viewer.entities.remove($this._sector);
          $this._sector = $this.createsector();
        }
      }
    }, $this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    this.handler.setInputAction(function (evt) {
      if (!$this._sector || $this._positions.length !== 3) return;
      var cartesian = $this.getCatesian3FromPX(evt.position);
      $this._positions.pop();
      $this._positions.push(cartesian);
      $this._sectorData = $this._positions.concat();
      $this.viewer.entities.remove($this._sector); //移除
      $this._sector = null;
      $this._positions = [];
      $this.floatingPoint.position.setValue(cartesian);
      var lnglatArr = [];
      for (var i = 0; i < $this._sectorData.length; i++) {
        var lnglat = $this.cartesianToLatlng($this._sectorData[i]);
        lnglatArr.push(lnglat)
      }
      $this._sectorData = lnglatArr;
      var sector = $this.addload(lnglatArr); //加载
      $this._entities_sector.push(sector);
      $this._sectorLast = sector;
      $this.clearPoint();
      $this.destroyDrawHandler();
      $this.bindClickEvent(); // 绑定气泡提示事件
      $this.DrawEndEvent.raiseEvent(sector, lnglatArr); // 触发绘制结束事件
    }, $this.Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    this.DrawStartEvent.raiseEvent();
  }

  //创建直线扇形
  createsector() {
    var $this = this;
    var arrowEntity = $this.viewer.entities.add({
      polygon: {
        hierarchy: new $this.Cesium.CallbackProperty(
          function () {
            let pnts = $this._positions;
            if (pnts.length < 3) return new $this.Cesium.PolygonHierarchy([]);

            let center = $this.lonLatToMercator($this.cartesianToLatlng(pnts[0]));
            let pnt2 = $this.lonLatToMercator($this.cartesianToLatlng(pnts[1]));
            let pnt3 = $this.lonLatToMercator($this.cartesianToLatlng(pnts[2]));
            var radius = $this.MathDistance(pnt2, center);
            var startAngle = $this.getAzimuth(pnt2, center);
            var endAngle = $this.getAzimuth(pnt3, center);
            var pList = $this.getArcPoints(center, radius, startAngle, endAngle);
            pList.push(pnts[0], pList[0]);

            return new $this.Cesium.PolygonHierarchy(pList);
          }, false),
        show: true,
        fill: true,
        clampToGround: true,
        material: $this.Cesium.Color.AQUA.withAlpha(0.5)
      }
    });
    arrowEntity.id = $this.objId; // 设置唯一ID
    $this._entities_sector.push(arrowEntity);
    return arrowEntity;
  }

  //创建点
  createPoint(cartesian) {
    var $this = this;
    var point = this.viewer.entities.add({
      position: cartesian,
      point: {
        pixelSize: 10,
        color: $this.Cesium.Color.YELLOW,
      }
    });
    $this._entities_point.push(point);
    return point;
  }

  cartesianToLatlng(cartesian) {
    var latlng = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
    var lat = this.Cesium.Math.toDegrees(latlng.latitude);
    var lng = this.Cesium.Math.toDegrees(latlng.longitude);
    return [lng, lat];
  }

  lonLatToMercator(Latlng) {
    var E = Latlng[0];
    var N = Latlng[1];
    var x = E * 20037508.34 / 180;
    var y = Math.log(Math.tan((90 + N) * Math.PI / 360)) / (Math.PI / 180);
    y = y * 20037508.34 / 180;
    return [x, y];
  }

  WebMercator2lonLat(mercator) {
    let x = mercator[0] / 20037508.34 * 180;
    let ly = mercator[1] / 20037508.34 * 180;
    let y = 180 / Math.PI * (2 * Math.atan(Math.exp(ly * Math.PI / 180)) - Math.PI / 2);
    return [x, y];
  }

  //销毁绘制事件处理器
  destroyDrawHandler() {
    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
  }

  //销毁
  destroy() {
    this.destroyDrawHandler();
    this.destroyClickHandler();
    this.removeBubblePopup();
  }

  // 销毁点击事件处理器
  destroyClickHandler() {
    if (this.clickHandler) {
      this.clickHandler.destroy();
      this.clickHandler = null;
    }
  }

  clearPoint() {
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.entities.remove(this._entities_point[i]);
    }
    this._entities_point = [];
  }

  //清空实体对象
  clear() {
    this.destroy();
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.entities.remove(this._entities_point[i]);
    }
    for (var i = 0; i < this._entities_sector.length; i++) {
      this.viewer.entities.remove(this._entities_sector[i]);
    }
    this.floatingPoint = null;
    this._sector = null;
    this._sectorLast = null;
    this._positions = [];
    this._entities_point = [];
    this._entities_sector = [];
    this._sectorData = null;
    this.removeBubblePopup();
  }

  // 移除气泡提示
  removeBubblePopup() {
    if (this.bubblePopup) {
      this.bubblePopup.remove();
      this.bubblePopup = null;
    }
    this.bubbleEntityInfo = null;
  }

  getCatesian3FromPX(px) {
    var cartesian;
    var ray = this.viewer.camera.getPickRay(px);
    if (!ray) return null;
    cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
    return cartesian;
  }

  // 数学工具函数
  MathDistance(pnt1, pnt2) {
    return Math.sqrt(Math.pow(pnt1[0] - pnt2[0], 2) + Math.pow(pnt1[1] - pnt2[1], 2));
  }

  getAzimuth(startPoint, endPoint) {
    var azimuth;
    var angle = Math.asin(Math.abs(endPoint[1] - startPoint[1]) / this.MathDistance(startPoint, endPoint));

    if (endPoint[1] >= startPoint[1] && endPoint[0] >= startPoint[0]) {
      azimuth = angle + Math.PI;
    } else if (endPoint[1] >= startPoint[1] && endPoint[0] < startPoint[0]) {
      azimuth = Math.PI * 2 - angle;
    } else if (endPoint[1] < startPoint[1] && endPoint[0] < startPoint[0]) {
      azimuth = angle;
    } else if (endPoint[1] < startPoint[1] && endPoint[0] >= startPoint[0]) {
      azimuth = Math.PI - angle;
    }

    return azimuth;
  }

  getArcPoints(center, radius, startAngle, endAngle) {
    var x = null, y = null, z = null, pnts = [],
      angleDiff = endAngle - startAngle;
    angleDiff = angleDiff < 0 ? angleDiff + Math.PI * 2 : angleDiff;

    for (var i = 0; i <= 100; i++) {
      var angle = startAngle + angleDiff * i / 100;
      x = center[0] + radius * Math.cos(angle);
      y = center[1] + radius * Math.sin(angle);
      let latlon = this.WebMercator2lonLat([x, y])
      pnts.push(this.Cesium.Cartesian3.fromDegrees(latlon[0], latlon[1]));
    }
    return pnts;
  }

  // 创建气泡提示
  createBubblePopup(position, entityInfo) {
    this.removeBubblePopup();
    if (!entityInfo || !position) return;

    let data = entityInfo.attr.formdata;

    // 创建气泡元素
    let bubblePopup = document.createElement("div");
    bubblePopup.id = "sector-bubble-popup";

    // 设置气泡样式
    bubblePopup.style.cssText = `
      position: absolute;
      background-color: rgba(0, 60, 136, 0.7);
      color: white;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 14px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.3);
      z-index: 1000;
      pointer-events: none;
      max-width: 250px;
      transition: opacity 0.2s ease;
    `;

    // 设置气泡内容
    bubblePopup.innerHTML = `
      <div style="font-weight: bold; margin-bottom: 4px;">${data.LayerName}</div>
      <div>${data.DesValue || "无描述信息"}</div>
    `;

    // 添加到地图容器
    let mapContainer = this.viewer.container;
    mapContainer.appendChild(bubblePopup);

    // 保存气泡引用
    this.bubblePopup = bubblePopup;
    this.bubbleEntityInfo = entityInfo;

    // 更新气泡位置
    this.updateBubblePopupPosition(position);
  }

  // 更新气泡位置
  updateBubblePopupPosition(position) {
    if (!this.bubblePopup) return;

    // 如果传入了位置，直接使用
    if (position) {
      this.bubblePopup.style.left = (position.x + 15) + "px";
      this.bubblePopup.style.top = (position.y - 15) + "px";
      return;
    }

    // 否则从实体计算位置
    let entity = this.bubbleEntityInfo.getEntity();
    let positions = entity.polygon.hierarchy.getValue(this.viewer.clock.currentTime).positions;

    if (!positions || positions.length === 0) return;

    // 计算多边形中心
    let center = this.Cesium.BoundingSphere.fromPoints(positions).center;

    // 转换为屏幕坐标
    let screenPosition = this.Cesium.SceneTransforms.wgs84ToWindowCoordinates(
      this.viewer.scene,
      center
    );

    if (screenPosition) {
      this.bubblePopup.style.left = (screenPosition.x + 15) + "px";
      this.bubblePopup.style.top = (screenPosition.y - 15) + "px";
    }
  }

  // 绑定点击事件
  bindClickEvent() {
    let that = this;

    // 先销毁已有的点击处理器
    this.destroyClickHandler();

    // 创建新的点击处理器
    this.clickHandler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

    // 左键点击显示气泡
    this.clickHandler.setInputAction(function (evt) {
      let pick = that.viewer.scene.pick(evt.position);

      // 检查是否点击了扇形
      if (that.Cesium.defined(pick) && pick.id && pick.id.Type === 'DrawSector') {
        // 查找对应的扇形实体
        for (let i = 0; i < that._entities_sector.length; i++) {
          if (pick.id.id === that._entities_sector[i].id) {
            let entityInfo = {
              attr: {
                formdata: {
                  LayerName: '扇形区域',
                  DesValue: '这是一个扇形区域，可用于表示覆盖范围'
                }
              },
              getEntity: function () {
                return that._entities_sector[i];
              }
            };

            // 创建气泡提示
            that.createBubblePopup(evt.position, entityInfo);
            break;
          }
        }
      } else {
        // 点击空白处移除气泡
        that.removeBubblePopup();
      }
    }, this.Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 监听相机移动事件，更新气泡位置
    this.viewer.camera.changed.addEventListener(() => {
      if (that.bubblePopup && that.bubbleEntityInfo) {
        that.updateBubblePopupPosition();
      }
    });
  }
}

export default DrawSector;